package com.edgar.thread.ch02;

import java.io.IOException;
import java.math.BigInteger;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import com.edgar.thread.annotation.NotThreadSafe;

/**
 * ++count不是原子操作:获得当前值，加1，写回新值，这样会导致遗失更新
 * 
 * 在并发变成中，这种由于不恰当的执行时序而出现不正确的结果是一种非常重要的情况， 它有一个正式的名字：竞态条件（Race Condition）
 * 当某个计算的正确性取决于多个线程的交替执行时序时，那么就会发生竞态条件
 * 最常见的竞态条件就是“先检查后执行(Check-Then-Act)”操作，即通过一个可能失效的观测结果来决定下一步的动作
 * 
 * @author Administrator
 * 
 */
@NotThreadSafe
public class UnsafeCountingFactorizer extends HttpServlet {

	private long count = 0;

	public long getCount() {
		return count;
	}

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		BigInteger i = extractFromRequest(request);
		BigInteger[] factors = factor(i);
		++count;
		encodeIntoResponse(response, factors);
	}

	private void encodeIntoResponse(ServletResponse response,
			BigInteger[] factors) {
		// TODO Auto-generated method stub

	}

	private BigInteger[] factor(BigInteger i) {
		// TODO Auto-generated method stub
		return null;
	}

	private BigInteger extractFromRequest(ServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}
}